package org.zh.home.utils;

import java.util.ArrayList;
import java.util.List;

import org.zh.home.model.Operate;
import org.zh.home.model.Param;
import org.zh.home.model.Query;
import org.zh.home.model.Separator;

public class QueryUtils {
	private static final String BACK = " ";
	/**
	 * 根据查询对象生成 查询对象
	 * @param hql    base HQL  如：from Group
	 * @param alias  别名   如 ：g  -->  from Group g
	 * @param model  参数模型 、根据该参数、获取值
	 * @return 查询对象
	 */
	public static Param generateHQLBase(String hql,String alias,List<Query> model) {
		Param param = new Param();
		StringBuilder build = new StringBuilder(hql);
		build.append(BACK);
		build.append(alias);
		build.append(BACK+"where 1=1");
		List<Object> values = new ArrayList<Object>();
		if(model != null) {
			for(Query obj:model) {
				build.append(BACK+obj.getSeparator()+BACK+alias+Separator.DOT+obj.getName());
				build.append(BACK+obj.getOperate()+BACK);
				if(obj.getOperate().equals(Operate.IN)) {
					build.append("("+obj.getValue()+")");
				} else if(obj.getOperate().equals(Operate.EQ)){
					build.append("'%"+obj.getValue()+"%'");
				} else {
					build.append(Separator.$);
					values.add(obj.getValue());
				}
			}
			param.setValues(values);
		}
		
		param.setQuery(build.toString());
		return param;
	}
}
